﻿using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;

using Mystery.SharePoint;

namespace Mystery.SharePoint.Services
{
    /// <summary>
    /// WCF service to support various Javascript activities
    /// </summary>
    [ServiceContract(Namespace= "http://sharepointmystery.com/soap")]
    public interface IJavaScriptSupport
    {
        [OperationContract()]
        [WebInvoke(Method = "GET", 
            BodyStyle = WebMessageBodyStyle.Wrapped, 
            ResponseFormat = WebMessageFormat.Json,
            UriTemplate = "/CreateLinkEmailBody?l={library}&ids={items}")]
        string CreateLinkEmailBody(string library, string items);
    }

    [ServiceBehavior(Namespace="http://sharepointmystery.com/soap")]
    [AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]
    //[SharePointPermission(System.Security.Permissions.SecurityAction.Demand, ObjectModel=true)]
    [Guid("f6f8C82a-301b-4e23-ab17-23fe55a15166")] //TODO: get the token replacement system to use this in SVC file
    public class JavaScriptSupport : IJavaScriptSupport
    {
        public string CreateLinkEmailBody(string listId, string itemIds)
        {
            if (string.IsNullOrEmpty(listId) == true)
            {
                return "No list was specified";
            }
            if (string.IsNullOrEmpty(itemIds) == true)
            {
                return "No items were specified";
            }

            SPWeb web = SPContext.Current.Web;
            Guid id = new Guid(listId);
            SPList list = web.Lists[id];

            string[] ids = itemIds.Split(",".ToCharArray());

            StringBuilder result = new StringBuilder();
            foreach (var item in ids)
            {
                // not optimal calling GetItemById, but setting up a CAML query with an unknown amount of OR's is not 
                // straight forward. May update this some time in the future. 
                SPListItem listItem = list.GetItemByIdAllFields(int.Parse(item));

                // set default values.
                string name = null;
                string url = web.Url.EnsureTrail("/") + listItem.Url;

                // some libraries do not have a title field. i.e wiki page library
                if (listItem.Fields.FindById(SPBuiltInFieldId.Title) != null)
                {
                    object obj = listItem[SPBuiltInFieldId.Title];
                    if (obj != null)
                    {
                        name = obj.ToString();
                    }
                }

                // if the DocumentID field is present, use that instead.
                if (listItem.Fields.TryGetFieldByStaticName("_dlc_DocIdUrl") != null)
                {
                    // a document id may not have been assigned yet
                    object obj = listItem["_dlc_DocIdUrl"];
                    if (obj != null)
                    {
                        SPFieldUrlValue value = new SPFieldUrlValue(obj.ToString());
                        url = value.Url;
                    }
                }
                // no title and has a file name, use that instead
                if((string.IsNullOrEmpty(name) == true) &&
                    (listItem.Fields.FindById(SPBuiltInFieldId.FileLeafRef) != null))
                {
                    name = listItem[SPBuiltInFieldId.FileLeafRef].ToString();
                }
                result.AppendFormat("{0}:{1}", 
                    (string.IsNullOrEmpty(name) == false) ? name : "No name", 
                    web.Site.RebaseUrl(url));
                result.Append(Environment.NewLine);
            }
            return result.ToString(); 
        }
    }
}
